package de.tum.in.eist.poll.client.widgets.content;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FormPanel;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.PasswordTextBox;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;

import de.tum.in.eist.poll.client.PollService;
import de.tum.in.eist.poll.client.PollServiceAsync;
import de.tum.in.eist.poll.shared.User;

/**
 * the Login UI, a Factory product
 * @author aperture
 *
 */
public class LoginUI extends Composite implements Content {
	protected static final PollServiceAsync pollService = GWT.create(PollService.class);

	private Widget initialization() {

		final FormPanel form = new FormPanel();

		final Label txtUser = new Label("Benutzer:");
		final TextBox inpUser = new TextBox();
		inpUser.setName("username");

		final Label txtPw = new Label("Passwort:");
		final TextBox inpPw = new PasswordTextBox();
		inpPw.setName("password");

		final Button btLogIn = new Button("Login");
		btLogIn.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				pollService.login(inpUser.getText(), inpPw.getText(),
						new AsyncCallback<User>() {

							@Override
							public void onSuccess(User result) {
								// TODO redirect to main page, firing ValueChangeHandler
								History.newItem("main", true);
							}

							@Override
							public void onFailure(Throwable caught) {
								Window.alert("callback failed.\nError details: "
										+ caught.getMessage());
							}
						});
			}
		});

		final Grid grid = new Grid(3, 2);
		{
			grid.setWidget(0, 0, txtUser);
			grid.setWidget(0, 1, inpUser);
			grid.setWidget(1, 0, txtPw);
			grid.setWidget(1, 1, inpPw);
			grid.setWidget(2, 1, btLogIn);
		}

		form.add(grid);

		return form;
	}

	@Override
	public Widget draw() {
		History.newItem("login", false);
		initWidget(initialization());
		return this;
	}
}
